using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Helpers;
using MVCWeb.Models;
using System.Web.Security;
using System.Globalization;
using System.Text;

namespace MVCWeb.Controllers
{
    public class UserController : BaseController
    {

        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.

        public UserController()
            : this(null, null)
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments at the end of this file for more
        // information.
        public UserController(IFormsAuthentication formsAuth, IMembershipService service)
        {
            FormsAuth = formsAuth ?? new FormsAuthenticationService();
            MembershipService = service ?? new AccountMembershipService();
        }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }
        //
        // GET: /User/
        [Authorize(Roles = "Administrators")]
        public ActionResult Index()
        {
            return View(dc.Users.OrderBy(u => u.LogInID));
        }

        //
        // GET: /User/Details/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /User/Create
        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            ViewData["Community"] = new SelectList(dc.Communities, "CommunityId", "Name");
            return View();
        }

        //
        // POST: /User/Create

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                string userName = collection["UserName"];
                string password = collection["Password"];
                string confirmPassword = collection["ConfirmPassword"];
                string fname = collection["FName"];
                string lname = collection["LName"];
                string email = collection["Email"];
                string hphone = collection["HPhone"];
                string address = collection["Address1"];
                string options = collection["Options"];
                string rolename = collection["RoleName"];
                string active = collection["Active"];
                string newsLetter = collection["NewsLetter"];
                int communityId = Convert.ToInt32(collection["CommunityId"]);

                // Attempt to register the user.
                MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    // Add new user to role: Users.
                    Roles.AddUserToRole(userName, rolename);

                    // Create my user.
                    MVCWeb.Models.User user = new User();
                    MembershipUser muser = Membership.GetUser(userName);
                    user.MembershipId = new Guid(muser.ProviderUserKey.ToString());
                    user.LogInID = userName;
                    user.Email = email;
                    user.Active = active != "false";
                    user.NewsLetter = newsLetter != "false";
                    user.Options = options;
                    user.FName = fname;
                    user.LName = lname;
                    user.HPhone = hphone;
                    user.Address1 = address;
                    user.UserType = rolename;
                    this.dc.Users.InsertOnSubmit(user);
                    this.dc.SubmitChanges();

                    // Status of muser.
                    muser.IsApproved = user.Active;
                    Membership.UpdateUser(muser);

                    // Add user to community.
                    UsersInCommunity uc = new UsersInCommunity();
                    uc.UserId = user.UserId;
                    uc.CommunityId = communityId;
                    this.dc.UsersInCommunities.InsertOnSubmit(uc);
                    this.dc.SubmitChanges();

                    if (collection["IsRedirectToView"].Equals("true"))
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return Redirect(Request.RawUrl);
                    }

                    //string code = user.MembershipId.Value.ToString();
                    //StringBuilder body = new StringBuilder();
                    //body.AppendFormat("Dear <strong>{0}</strong>!<br><br>", userName);
                    //body.AppendFormat("Thank you for registering at the <a href='{0}'><strong>{1}</strong></a>. Before we can activate your account one last step must be taken to complete your registration. You will only need to visit this URL once to activate your account.<br><br>", "http://www.leisure-life.com", "Leisure-Life");
                    //body.Append("To complete your registration, please visit this URL:<br />");
                    //body.AppendFormat("<a href='{0}' target='_blank'>{0}</a><br /><br />", "http://www.leisure-life.com" + Url.Action("ActiveUser", "Account", new { UserId = user.MembershipId.Value.ToString() }));
                    //body.Append("Please be sure not to add extra spaces. You will need to type in your username and activation number on the page that appears when you visit the URL.<br /><br /><br />");


                    //body.AppendFormat("Your Username is: {0}<br />", userName);
                    //body.AppendFormat("Your Password is: {0}<br /><br /><br />", password);
                    //body.Append("If you are still having problems signing up please contact a member of our support staff at webmaster@leisure-life.com <br /><br /><br />");
                    //body.AppendFormat("All the best, <br /> Leisure-Life");

                    //MailHelper.SendMail("webmaster@leisure-life.com", email, "", "ngothanhtung.it@gmail.com", "Leisure - Life (Action Required to Activate Membership for Leisure-Life)", body.ToString(), System.Net.Mail.MailPriority.High);
                }
                else
                {
                    ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                }
                ViewData["Community"] = new SelectList(dc.Communities, "CommunityId", "Name");
                return View();
            }
            catch
            {
                ViewData["Community"] = new SelectList(dc.Communities, "CommunityId", "Name");
                return View();
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        
        [Authorize(Roles = "Administrators")]
        public ActionResult ResetPassword(int id)
        {
            User user = this.dc.Users.Single<User>(u => u.UserId == id);
            return View(user);
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult ResetPassword(int id, FormCollection collection)
        {
            try
            {
                // Change password.
                User user = this.dc.Users.Single<User>(u => u.UserId == id);
                MembershipUser mu = Membership.GetUser(user.LogInID);
                mu.UnlockUser();
                mu.ChangePassword(mu.ResetPassword(), collection["NewPassword"]);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }




        //
        // GET: /User/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id)
        {
            User user = this.dc.Users.Single<User>(u => u.UserId == id);
            string[] roles = System.Web.Security.Roles.GetRolesForUser(user.LogInID);
            if (roles.Length > 0)
            {
                ViewData["RoleName"] = new SelectList(System.Web.Security.Roles.GetAllRoles(), roles[0]);
            }
            else
            {
                ViewData["RoleName"] = new SelectList(System.Web.Security.Roles.GetAllRoles(), "Users");
            }
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                string rolename = collection["RoleName"];
                string fname = collection["FName"];
                string lname = collection["LName"];
                string email = collection["Email"];
                string hphone = collection["HPhone"];
                string address = collection["Address1"];
                string options = collection["Options"];
                string active = collection["Active"];
                string newsLetter = collection["NewsLetter"];

                User user = this.dc.Users.SingleOrDefault(u => u.UserId == id);

                if (Roles.IsUserInRole(user.LogInID, "administrators"))
                    Roles.RemoveUserFromRole(user.LogInID, "administrators");

                if (Roles.IsUserInRole(user.LogInID, "managers"))
                    Roles.RemoveUserFromRole(user.LogInID, "managers");

                if (Roles.IsUserInRole(user.LogInID, "users"))
                    Roles.RemoveUserFromRole(user.LogInID, "users");

                Roles.AddUserToRole(user.LogInID, rolename.ToLower());
                user.Active = active != "false";
                user.NewsLetter = newsLetter != "false";
                user.FName = fname;
                user.LName = lname;
                user.Email = email;
                user.HPhone = hphone;
                user.Address1 = address;
                user.Options = options;
                dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                return Redirect(Request.RawUrl);
            }
            catch
            {
                return View();
            }
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult ChangeStatus(int id)
        {
            User user = this.dc.Users.First(x => x.UserId == id);
            user.Active = !user.Active;
            this.dc.SubmitChanges();

            MembershipUser mu = Membership.GetUser(user.LogInID);
            mu.IsApproved = !mu.IsApproved;
            Membership.UpdateUser(mu);
            return View();
        }

    }
}
